import { ProList } from '@ant-design/pro-components';
import { Badge, Button, Space, Tag, Cascader, Input } from 'antd';
import type { ActionType } from '@ant-design/pro-components';
import React, {useRef, useState, Key, useEffect} from 'react';
import type { SearchProps } from 'antd/es/input/Search';
import {listTeamsUsingGet} from "@/services/openAPI-backend/teamController";


// 普通搜索
const { Search } = Input;
const onSearch: SearchProps['onSearch'] = (value, _e, info) => console.log(info?.source, value);

// 级联搜索
interface Option {
  value: string | number;
  label: string;
  children?: Option[];
  disableCheckbox?: boolean;
}
const options: Option[] = [
  {
    label: 'Light',
    value: 'light',
    children: new Array(20)
      .fill(null)
      .map((_, index) => ({ label: `Number ${index}`, value: index })),
  },
  {
    label: 'Bamboo',
    value: 'bamboo',
    children: [
      {
        label: 'Little',
        value: 'little',
        children: [
          {
            label: 'Toy Fish',
            value: 'fish',
            disableCheckbox: true,
          },
          {
            label: 'Toy Cards',
            value: 'cards',
          },
          {
            label: 'Toy Bird',
            value: 'bird',
          },
        ],
      },
    ],
  },
];


const renderBadge = (count: number, active = false) => {
  return (
    <Badge
      count={count}
      style={{
        marginBlockStart: -2,
        marginInlineStart: 4,
        color: active ? '#1890FF' : '#999',
        backgroundColor: active ? '#E6F7FF' : '#eee',
      }}
    />
  );
};

export default () => {
  const [expandedRowKeys, setExpandedRowKeys] = useState<readonly Key[]>([]);
  const [activeKey, setActiveKey] = useState<React.Key | undefined>('tab1');
  const action = useRef<ActionType>();
  const [listData, setListData] = useState([]);

  const LoadingData = async (current: number, pageSize: number) => {
    try {
      const res = await listTeamsUsingGet({
       current,
        pageSize,
      })
      if (res.data){
        setListData(res.data)
      }
    }catch (e) {

    }
}
  const dataSource = listData.map((item) => {

   return {
      name: item.teamName,
     avatar:item.teamAvatar,
      desc: item.description,
      member: item.maxMum,
     isPublic: true,
     content: [{label:'标签',value:item.tags.split("'")[1]},{}],
     subTitle: item.tags.split("'")[1],
   }

})
// 动态生成列表项操作按钮
  const renderActions = (text, row) => {
    let buttonStyle = { marginRight: '10px' }; // 定义按钮样式，右侧间距10px

    if (activeKey === 'tab1') {
      // 对于"全部团队"，只提供退出操作，并应用样式
      return [
        <a key="quit" style={buttonStyle} onClick={() => alert(`退出 ${row.name}`)}>退出</a>,
      ];
    } else if (activeKey === 'tab2') {
      // 对于"我创建的"，提供邀请、编辑、解散操作，并应用样式
      return [
        <a key="invite" style={buttonStyle} onClick={() => alert(`邀请至 ${row.name}`)}>邀请</a>,
        <a key="edit" style={buttonStyle} onClick={() => alert(`编辑 ${row.name}`)}>编辑</a>,
        <a key="dissolve" style={{ ...buttonStyle, color: 'red' }} onClick={() => alert(`解散 ${row.name}`)}>解散</a>,
      ];
    }
    return [];
  };
  useEffect(() => {
    LoadingData(1, 10);
  }, []);

  return (
    <div style={{width: '100%', marginTop: 20}}>
    <ProList<any>
      rowKey="name"
      actionRef={action}
      expandable={{ expandedRowKeys, onExpandedRowsChange: setExpandedRowKeys }}
      dataSource={dataSource}
      editable={{}}

      // 列表项
      metas={{
        title: {
          title: 'Name',
          dataIndex: 'name',
          valueType: 'select',
          fieldProps: {
            showSearch: true,
            placement: 'bottomRight',
            options: [
              {
                label: '实验名称1',
                value: '实验名称1',
              },
            ],
          },
          render: (text) => <span style={{ fontSize: 16, margin: 4 }}>{text}</span>,
        },

        description: {
          dataIndex: 'desc',
          render: (item) => {
           return(
             item
           )
          },
        },

        avatar: {
          dataIndex: 'avatar',
        },

        // 标签
        subTitle: {
          render: (item) => {
            return (
              <Space size={5}>
                <Tag color="blue">E-API</Tag>
                <Tag color="#5BD8A6">{item}</Tag>
              </Space>
            );
          },
        },

        content: {
          dataIndex: 'content',
          render: (text) => (
            <div style={{ display: 'flex', justifyContent: 'right' }}> {/* 修改justifyContent为'start'或根据需求调整 */}
              {(text as any[]).map((t, index) => (
                <div key={`${t.label}-${index}`} style={{ marginRight: 50 }}>
                  <div>{t.label}</div>
                  <div>
                    {t.status === 'success' && (
                      <span
                        style={{
                          display: 'inline-block',
                          width: 8,
                          height: 8,
                          borderRadius: '50%',
                          backgroundColor: '#52c41a',
                          marginInlineEnd: 8,
                        }}
                      />
                    )}
                    {t.value}
                  </div>
                </div>
              ))}
            </div>
          ),
        },

        actions: {
          render: (text, row) => renderActions(text, row),
        },
      }}

      // 顶部工具栏
      toolbar={{
        menu: {
          activeKey,
          items: [
            {
              key: 'tab1',
              label: (
                <span style={{fontSize : 18, marginBottom:5, borderBottom: '2px solid #red'}}>
                  全部团队{renderBadge(listData.length, activeKey === 'tab1')}
                </span>
              ),
            },
            {
              key: 'tab2',
              label: (
                <span style={{fontSize : 18, marginBottom:5, borderBottom: '2px solid #red'}}>
                  我创建的团队{renderBadge(3, activeKey === 'tab2')}
                </span>
              ),
            },
          ],
          onChange(key) {
            setActiveKey(key);
          },
        },

        actions: [
          <Search
            placeholder="队名搜索" onSearch={onSearch} style={{ width: 300, marginRight: 10 }} />,

          // 新增级联选择器
          <Cascader
            style={{ width: 300}}
            options={options} // 这里是级联选项的数据源，你需要根据实际情况定义
            placeholder="标签搜索"
            onChange={(value, selectedOptions) => {
              console.log('Selected: ', value, selectedOptions);
              // 在这里处理级联选择器的值变化事件
            }}
            multiple
            maxTagCount="responsive"
            key="cascader" // 为Cascader组件添加一个key
          />,

          <Button type="primary" key="primary" style={{fontSize : 16}}>
            新建团队
          </Button>,

        ],
      }}
      />
    </div>
  );
};
